package com.example.dao;

import java.util.ArrayList;
import java.util.List;

import com.example.dao.DatabaseUtility.DatabaseHelper;
import com.example.vo.user;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class UserProfileDAO {
	private static final String USER_PROFILE = "USER_PROFILE";
	private static final String DATABASE_NAME = "FTICO_DATABASE";
	private static final int DATABASE_VERSION = 1;

	private static final String USER_ID = "USER_ID";
	private static final String USER_NAME = "USER_NAME";
	private static final String CREATE_AT = "CREATE_AT";
	private static final String UPDATE_AT = "UPDATE_AT";
	public static final String DELETE_FLG = "DELETE_FLG";

	private Context mContext;
	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDB;

	public UserProfileDAO(Context ctx) {
		mContext = ctx;
	}

	public UserProfileDAO open() {
		mDbHelper = new DatabaseHelper(mContext, DATABASE_NAME, null,
				DATABASE_VERSION);
		mDbHelper.set_mContext(mContext);
		mDB = mDbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		mDbHelper.close();
	}

	public void update() {
		mDbHelper.onUpgrade(mDB, DATABASE_VERSION, 2);
	}

	public long insertProfile(String nickname, String createAt, String updateAt) {
		ContentValues values = new ContentValues();
		values.put(USER_NAME, nickname);
		values.put(CREATE_AT, createAt);
		values.put(UPDATE_AT, updateAt);
		values.put(DELETE_FLG, 0);
		return mDB.insert(USER_PROFILE, null, values);
	}

	public user getUserByID(int userID) {
		user _user = new user();
		Cursor cursor = mDB.query(USER_PROFILE, null, "USER_ID = " + userID
				+ " AND DELETE_FLG = 0", null, null, null, null);
		if (cursor.moveToFirst()) {
			_user.setId(Integer.parseInt(cursor.getString(0)));
			_user.setUser(cursor.getString(1));
			_user.setCreateAt(cursor.getString(2));
			_user.setUpdateAt(cursor.getString(3));
		}
		cursor.close();
		return _user;
	}

	public List<user> getAllUser() {
		List<user> _userList = new ArrayList<user>();
		Cursor cursor = mDB.query(USER_PROFILE, null, "DELETE_FLG = 0", null,
				null, null, null);
		if (cursor.moveToFirst()) {
			user _user = new user();
			_user.setId(Integer.parseInt(cursor.getString(0)));
			_user.setUser(cursor.getString(1));
			_user.setCreateAt(cursor.getString(2));
			_user.setUpdateAt(cursor.getString(3));
			_userList.add(_user);
		}
		while (cursor.moveToNext())
			;
		return _userList;
	}
}
